package datetime

import (
	"context"
	"fmt"
	"github.com/beherochuling/beesoft_api/app/helper/net"
	thisModel "github.com/beherochuling/beesoft_api/app/model/util/date"

	"github.com/beherochuling/beesoft_api/app/dao"
	"github.com/beherochuling/beesoft_api/app/model/apps"
	"github.com/beherochuling/beesoft_api/app/model/entity"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"
)

func (r *datetime) Period(ctx context.Context, parentId uint) []entity.AppsDatetimePeriods {
	var items []entity.AppsDatetimePeriods
	err := dao.AppsDatetimePeriods.Ctx(ctx).
		Where(dao.AppsDatetimePeriods.Columns().ParentId, parentId).
		Scan(&items)
	if err != nil {
		panic(err)
	}

	return items
}
func (r *datetime) PeriodList(ctx context.Context, req *thisModel.PeriodReq) (map[uint]*apps.DatetimePeriodItem, *net.Exception) {
	//result := r.Period(ctx, 0)
	//
	//for _, item := range result {
	//	item.
	//}
	//
	return nil, nil
}

func (r *datetime) PeriodInsert(ctx context.Context, item apps.RegionItem) int64 {
	id, err := dao.AppsDatetimePeriods.Ctx(ctx).
		InsertAndGetId(entity.AppsDatetimePeriods{
			ParentId:   item.ParentId,
			Name:       item.Name,
			Title:      item.Title,
			Remark:     item.Remark,
			StartedAt:  gtime.New(item.Start),
			FinishedAt: gtime.New(item.End),
			Start:      item.Start,
			Finish:     item.End,
		})
	if err != nil {
		panic(err)
	}

	return id
}
func (r *datetime) PeriodSync(ctx context.Context) {
	filePath := "F:\\docker\\subject\\history\\纪年.md"
	data := gfile.GetBytes(filePath)

	var dynasties []apps.Dynasties
	err := gconv.Structs(data, &dynasties)
	if err != nil {
		panic(err)
	}

	for _, dynasty := range dynasties {
		dynasty.Id = r.PeriodInsert(ctx, dynasty.RegionItem)

		for _, emperor := range dynasty.Emperors {
			emperor.ParentId = uint(dynasty.Id)
			emperor.Id = r.PeriodInsert(ctx, emperor.RegionItem)

			for _, reign := range emperor.Reigns {
				reign.ParentId = uint(emperor.Id)
				reign.Id = r.PeriodInsert(ctx, reign)
			}
		}
	}

	fmt.Printf("Parsed Struct: %+v ", dynasties)
}
